/**
 * 
 */
package com.ly.hotel.view.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ly.hotel.R;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.msgevent.UpdateBottomView;
import com.ly.hotel.msgevent.UpdateMessageView;
import com.ly.hotel.util.TouchUtil;
import com.ly.hotel.view.fragments.about.AboutDialog;

import org.json.JSONArray;
import org.json.JSONException;

import de.greenrobot.event.EventBus;

public class Bottom extends LinearLayout {
	private Context context;

	private ImageView logoView;
	private AboutDialog adDialog = null;
	private View view;
	private RecyclerView recyclerView;
	private LinearLayout left;
	private LinearLayout right;
	private LinearLayoutManager linearLayoutManager;
	private bottomAdapter bAdapter;

	MyApplication app;
	private List<BottomItemInfo> btnList = new ArrayList<>();
	

	public Bottom(final Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		app = (MyApplication)(this.context.getApplicationContext());
		EventBus.getDefault().register(this);
		view = LayoutInflater.from(getContext()).inflate(R.layout.bottom, this);
		logoView = view.findViewById(R.id.module_logo);
		recyclerView = view.findViewById(R.id.bottom_recycle);
		left = view.findViewById(R.id.left_more);
		right = view.findViewById(R.id.right_more);
		linearLayoutManager = new LinearLayoutManager(context);
		linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		recyclerView.setLayoutManager(linearLayoutManager);
		logoView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(adDialog == null) {
					adDialog = new AboutDialog(MyApplication.getContext(), R.style.introDialog);
					adDialog.setCanceledOnTouchOutside(true);
					adDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
				}
				adDialog.show();
				adDialog.setRoomVer();
			}
		});
		creatBtn();
		checkLogo();
		setListener();
	}

	private void setListener(){
		recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
			@Override
			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
				super.onScrolled(recyclerView, dx, dy);
			}

			@Override
			public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
				super.onScrollStateChanged(recyclerView, newState);
				checkArrow();
			}
		});
	}

	//是否显示箭头提示
	private void checkArrow(){
		if (recyclerView.canScrollHorizontally(1)){
			right.setVisibility(VISIBLE);
		}else{
			right.setVisibility(INVISIBLE);
		}

		if (recyclerView.canScrollHorizontally(-1)){
			left.setVisibility(VISIBLE);
		}else{
			left.setVisibility(INVISIBLE);
		}
	}

	private void checkLogo(){
		if(SysConf.extendConfGetValue(SysConf.SYS_CONF_LOGO_ENABLE,"1").equals("0")){
			logoView.setVisibility(View.INVISIBLE);
			setLogo();
		}
	}

	private void updateBottomMsg(){
		int num = 0;
		int pos = -1;
		List<HotelMassage> hotelMassages = app.getRtMsgList();
		for(HotelMassage hm : hotelMassages){
			if(!hm.getRead()){
				num ++;
			}
		}
		for(BottomItemInfo bi : btnList){
			if(bi.getName().equals("消息")){
				bi.setMsgNum(num);
				pos = btnList.indexOf(bi);
				break;
			}
		}

		if (bAdapter != null && pos > -1){
			bAdapter.notifyItemChanged(pos);
		}
	}

	private void creatBtn() {
		btnList.clear();
		List<BottomItemInfo> bList = app.getBtnItemInfo();
		if(bList.size() == 0){
			Log.e("Bottom", "Bottom,半死不活，我要重生！！");
			//出现这个问题，可能是程序崩溃了，重启自己吧
			System.exit(0);
			return;
		}
		for (BottomItemInfo bi : bList) {
			if(bi.isEnable()){
				btnList.add(bi);
			}
		}
		//按钮排序
		if(!TextUtils.isEmpty(app.homeSort)){
			try {
				JSONArray arr = new JSONArray(app.homeSort);
				for (int i = arr.length() -1; i >= 0; i--) {
					String lan = arr.getString(i);
					for (BottomItemInfo b : btnList) {
						if(lan.equals(b.getName())) {
							btnList.remove(b);
							btnList.add(0,b);
							break;
						}
					}
				}
			}catch (JSONException e){
				Log.e("Bottom",e.getMessage());
			}
		}

		int num = 0;
		List<HotelMassage> hotelMassages = app.getRtMsgList();
		if(hotelMassages.size() > 0) {
			for (HotelMassage hm : hotelMassages) {
				if (!hm.getRead()) {
					num++;
				}
			}
			for (BottomItemInfo bi : btnList) {
				if (bi.getName().equals("消息")) {
					bi.setMsgNum(num);
					break;
				}
			}
		}
		setAdapter();
	}

	private void setLogo(){
		if (MyApplication.getLogoBitmap() != null) {
			logoView.setVisibility(View.VISIBLE);
			logoView.setImageBitmap(MyApplication.getLogoBitmap());
		} else {
			File f = new File(Constants.LOGO_FILE_PATH);
			if (f.exists()) {
				Bitmap bgImage = BitmapFactory.decodeFile(Constants.LOGO_FILE_PATH);
				if (bgImage != null) {
					logoView.setVisibility(View.VISIBLE);
					logoView.setImageBitmap(bgImage);
				}
			}
		}

	}

	private void setAdapter(){
		if (bAdapter == null){
			bAdapter = new bottomAdapter();
			recyclerView.setAdapter(bAdapter);
		}else{
			bAdapter.notifyDataSetChanged();
		}
		recyclerView.post(new Runnable() {
			@Override
			public void run() {
				recyclerView.requestFocus();
				recyclerView.requestFocusFromTouch();
				checkArrow();
			}
		});
	}
	

	public void onEventMainThread(UpdateBottomView event) {
		creatBtn();
	}

	public void onEventMainThread(UpdateMessageView event) {
		updateBottomMsg();
		recyclerView.post(new Runnable() {
			@Override
			public void run() {
				checkArrow();
			}
		});
	}


	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		EventBus.getDefault().unregister(this);
	}

	class bottomAdapter extends RecyclerView.Adapter<bottomAdapter.ViewHolder>{

		class ViewHolder extends RecyclerView.ViewHolder{
			View itemView;
			ImageView bottomImage;
			TextView bottomName;
			TextView msgCount;

			public ViewHolder(View view){
				super(view);
				itemView = view;
				bottomImage = view.findViewById(R.id.bottom_img);
				bottomName = view.findViewById(R.id.bottom_text);
				msgCount = view.findViewById(R.id.msg_count);
			}
		}

		public bottomAdapter(){}

		@Override
		public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
			View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bottom_item,parent,false);
			final ViewHolder holder = new ViewHolder(view);
			holder.itemView.setFocusable(true);
			holder.itemView.setClickable(true);
			holder.itemView.setBackgroundResource(R.drawable.shortcut_btn_background);
			holder.itemView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int pos = holder.getAdapterPosition();
					String btnName = btnList.get(pos).getName();
					if(app.getBtnItemRespond(btnName)){
						if(btnName.equals("呼叫") || btnName.equals("留位")){
							EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_BOTTOM_PREFIX + btnName));
						}
						TouchUtil.sendKeyCode(btnList.get(pos).getKeyCode(),0,true);
					}else{
						Toast.makeText(context, btnName + "模块没开通", Toast.LENGTH_SHORT).show();
					}
				}
			});
			return holder;
		}

		@Override
		public void onBindViewHolder(ViewHolder holder,int position) {
			BottomItemInfo btn = btnList.get(position);
			holder.bottomName.setText(btn.getShowName());
			holder.bottomImage.setImageResource(btn.getImgRes());
			holder.msgCount.setText(btn.getMsgNum()+"");
			if (btn.getMsgNum() > 0) {
				holder.msgCount.setVisibility(VISIBLE);
			}else{
				holder.msgCount.setVisibility(INVISIBLE);
			}
		}

		@Override
		public int getItemCount() {
			return btnList.size();
		}
	}
}
